<template>
  <v-layout type="project">
    <div slot="menuHeader">
      <!-- <change-project /> -->
    </div>
    <div>
      <div class="navbar clearfix" v-if="$route.meta.showIntroduce">
        <el-breadcrumb class="breadcrumb-container" separator="/">
          <el-breadcrumb-item :to="`/project/dataset/lis?id=${$route.query.id}`">私有数据集</el-breadcrumb-item>
          <el-breadcrumb-item class="defaultname">{{ detailData ? detailData.name : '' }}</el-breadcrumb-item>
        </el-breadcrumb>
        <span class="back">
          <el-button type="text" icon="el-icon-right" @click="
            $router.push({
              path: '/project/dataset/lis', query: { id: $route.query.id }
            })
          "></el-button>
        </span>
      </div>
      <div class="introduce" v-if="$route.meta.showIntroduce">
        <el-form class="form" label-width="120px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="ID">
                {{ detailData.id }} <i class="copy-btn el-icon-copy-document" v-clipboard:copy="`${detailData.id}`"
                  v-clipboard:success="onCopy" v-clipboard:error="onError"></i>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数据格式">
                {{ detailData.format ? detailData.format : '-' }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间">
                {{ formatTime(detailData.createTime) }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="名称" prop="name">
                <div v-if="!detailData.editName" class="edit-box">{{ detailData.name }} <i class="edit-i"
                    @click="editNameHandler"></i> </div>
                <div v-else>
                  <el-input type="text" class="edit-input" maxlength="40" v-model="detailData.name">
                    <template slot="append">
                      <el-button type="text" class="sml-btn" @click="putdetailHandler">确定</el-button>
                      <el-button type="text" class="sml-btn" @click="cancelEdit">取消</el-button>
                    </template>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="描述" prop="description">
                <div v-if="!detailData.editDescription" class="edit-box">{{ detailData.description }} <i class="edit-i"
                    @click="editDescriptionHandler"></i> </div>
                <div v-else>
                  <el-input type="text" class="edit-input" maxlength="40" v-model="detailData.description">
                    <template slot="append">
                      <el-button type="text" class="sml-btn" @click="putdetailHandler">确定</el-button>
                      <el-button type="text" class="sml-btn" @click="cancelEdit">取消</el-button>
                    </template>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人">
                <span v-if="detailData.createUser">{{ detailData.createUser.nickName ? detailData.createUser.nickName :
                  detailData.createUser.username }}</span>
                <span v-else>-</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="版本归属方" prop="name">
                {{ detailData.copyrightOwner ? detailData.copyrightOwner : '暂无' }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="应用场景" prop="description">
                {{ detailData.scene ? detailData.scene : '-' }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数据集官网">
                {{ detailData.link ? detailData.link : '暂无' }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="标注类型" prop="name">
                {{ detailData.labels }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="">
                <div class="btns">
                  <v-btn class="sml-btn" type="hollow" @click="showPublicDialog" v-if="isshow">共享</v-btn>
                  <v-btn class="sml-btn" type="hollow"
                    :to="{ path: '/project/dataset/detail', query: { id: $route.query.id, datasetid: $route.query.datasetid } }">修改</v-btn>
                  <v-btn class="sml-btn" type="hollow" @click="delHandler">删除</v-btn>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="inner-nav clearfix" v-if="$route.meta.showIntroduce">
        <ul class="nav">
          <li :class="[e.meta.icon, { 'active': e.name == $route.name }]" @click="skip(e)" v-for="(e, i) in nav" :key="i">
            {{ e.meta.title }}
          </li>
        </ul>
      </div>
    </div>
    <v-dialog :visible.sync="showPublic" title="共享数据集" width="800px">
      <el-form ref="forms" label-width="90px">
        <el-row>

          <h3 class="frees">{{ detailData.name }}</h3>
        </el-row>
        <el-row>
          <el-col :span="24" class="title-slider">
            <el-form-item label="共享版本：" label-width="120px">
              <el-select v-model="versions" filterable placeholder="请选择版本" multiple style="width:100%">
                <el-option v-for="item in  versionData" :key="item.id" :label="item.version" :value="item.id"></el-option>
              </el-select>
              <div class="dataset-tags-box">
                <p> 共享版本，共享成功后的数据集版本，即可被用户使用。</p>
                <p> 移除共享版本，移除后该版本记录(文件不会被删除)，不会影响已经引用的任务。</p>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <v-btn @click="cancelHandler">取消</v-btn>
        <v-btn type="primary" @click="publicHandler">确认</v-btn>
      </span>
    </v-dialog>
    <router-view />
  </v-layout>
</template>
<script>
// import changeProject from '@/views/project/module/change-project'
import { updateDataSet, detailDataSet, deleteDataSet, getVersionAll, datasetPublic } from '@/api/dataset'
// import { checkpublish } from '@/api/project'
import { formatTime } from "@/utils/tool"

export default {
  data() {
    return {
      detailData: {},
      backupData: {},  // backup detailData
      publicArray: [],
      versionData: [],
      versions: [],
      showPublic: false,
      isshow: true,
      nav: []
    };
  },
  components: {
    // changeProject
  },
  watch: {
    $route() {
      if (this.$route) {   // fix the same router ,no  trigger hook mounted
        this.getData()
      }
    }
  },
  methods: {
    formatTime,
    skip(e) {
      if (e.name == this.$route.name) return
      this.$router.push({
        path: `/project/dataset/${e.path}`,
        query: { ...this.$route.query }
      })
    },
    async getData() {
      let _id = this.$route.query.datasetid
      if (_id) {
        this.detailData = await detailDataSet({ id: _id })
        this.detailData.editName = false;
        this.detailData.editDescription = false;

        this.backupData = JSON.parse(JSON.stringify(this.detailData));
      }
    },
    editNameHandler() { // pre edit image  name
      this.detailData.editName = true;
      this.detailData.editDescription = false;
      this.detailData.description = this.backupData.description;
      this.$forceUpdate();
    },
    editDescriptionHandler() { // pre edit image  name
      this.detailData.editDescription = true;
      this.detailData.editName = false;
      this.detailData.name = this.backupData.name;
      this.$forceUpdate();
    },
    cancelEdit() { // cancel edit 
      this.detailData.editName = false;
      this.detailData.editDescription = false;
      this.detailData.name = this.backupData.name
      this.detailData.description = this.backupData.description
      this.$forceUpdate();
    },
    toDetail() {   // to detail
      this.$router.push({
        path: '/project/dataset/detail',
        query: { id: this.$route.query.id, datasetid: this.detailData.id }
      })
    },
    async deleteDataSet() { // delete image 
      let confirm = await this.$messesDialog({ message: "操作删除后,镜像文件被物理删除且不可恢复,请谨慎操作" });
      if (confirm) {
        let res = await deleteDataSet(this.detailData.id);
        if (res) {
          this.$router.push({ path: "/project/dataset/lis", query: { id: this.$route.query.id } });
        }
      }
    },
    async putdetailHandler() {
      if (!this.detailData.name) {
        this.$message.warning('名称不能为空')
        return false;
      }
      if (!this.detailData.description) {
        this.$message.warning('描述不能为空')
        return false;
      }
      let res = await updateDataSet(this.detailData)
      if (res) {
        this.$message.success('修改成功')
        this.getData();
      }
    },
    onCopy() {
      this.$message({
        message: "复制成功",
        type: "success",
      });
    },
    onError() {
      this.$message({
        message: "复制失败",
        type: "error",
      });
    },
    showPublicDialog() {
      this.showPublic = true;
      this.getVersionList(this.detailData.id);
    },
    cancelHandler() {
      this.showPublic = false;
    },
    async getVersionList(id) {
      let res = await getVersionAll({ id: id });
      this.versionData = res
      //过滤出当前数据集已经公开的版本
      this.publicArray = this.versionData.filter((item) => {
        return item.visibility === '0'
      })
      if (this.publicArray && this.publicArray.length > 0) {
        this.versions = this.publicArray.map((item) => {
          return item.id;
        })
      }
      else {
        this.versions = [];
      }
    },
    async publicHandler() { //公开数据集
      let originalArray = this.publicArray.map((item) => {
        return item.id;
      })
      let diff = originalArray.filter((item) => { return this.versions.indexOf(item) === -1 })
      if (diff && diff.length > 0) {
        //取消公开数据集
        let res = await datasetPublic({ datasetId: this.detailData.id, versions: diff, visibility: '1' })
        if (res) {
          //添加公开
          if (this.versions && this.versions.length > 0) {
            let publishres = await datasetPublic({ datasetId: this.detailData.id, versions: this.versions, visibility: '0' })
            if (publishres) {
              this.$message.success('操作成功')
              this.showPublic = false;
              this.getData();
            }
          }
          else {
            this.$message.success('操作成功')
            this.showPublic = false;
            this.getDataSet();
          }
        }
      }
      else {
        //添加公开
        if (this.versions && this.versions.length > 0) {
          let res = await datasetPublic({ datasetId: this.detailData.id, versions: this.versions, visibility: '0' })
          if (res) {
            this.$message.success('操作成功')
            this.showPublic = false;
            this.getData();
          }
        }
        else {
          this.$message.warning('请选择需要公开的版本')

        }
      }
    },
    //检查是否有发布权限
    // async checkPublishAuth () {
    //   checkpublish
    // this.isshow = await checkpublish();
    // },
    async delHandler() {
      let msg = '<p>操作删除后，数据集及全部版本数据都将会被物理删除且不可恢复，请谨慎操作</p>'
      if (this.detailData.visibility == '0') {
        msg = '<p>当前数据集已公开，仅删除数据集组和版本记录（文件不删除），不会影响已经引用的任务</p>'
      }
      console.log('msg', msg)
      let res = await this.$isDel(msg);
      if (res) {

        let rs = await deleteDataSet({
          id: this.detailData.id
        })
        if (rs) {
          this.$EventBus.$emit("notAdd", false);
          this.$message.success('删除成功')
          this.$router.push({ path: "/project/dataset/lis", query: { id: this.$route.query.id } })
        }
      }
    },
  },
  mounted() {
    this.getData()
    // this.checkPublishAuth();
    let temp = this.$router.options.routes.filter(
      e => e.name == 'projectdataset'
    )
    this.nav = temp[0].children.filter(
      e => e.inNav && e.meta.affiliation == 'dataset'
    )
  },
};
</script>

<style lang="less" scoped>
.layout {
  background: #F3F3F3;

  .navbar {
    min-width: 958px;
    padding: 12px 0px 0px 54px;

    .back {
      position: absolute;
      right: 16px;
      top: 16px;

      /deep/.el-icon-right {
        font-size: 20px;
      }
    }

    /deep/.el-breadcrumb__item {
      line-height: 45px;
    }
  }

  .introduce {
    min-width: 958px;
    min-height: 136px;
    margin: 0 16px 16px 16px;
    background: #fff;
    padding-top: 20px;
    margin-bottom: 10px;

    .form {
      margin: 0px 0px 8px 24px;

      /deep/.el-form-item {
        margin-bottom: 0px !important;
      }

      /deep/.el-form-item__label {
        text-align: left;
        width: 88px;
      }

      /deep/.el-form-item__content {
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 4;
        overflow: hidden;
        word-break: break-all;
      }

      .edit-box {
        display: inline-block;
      }

      .edit-i {
        margin-left: 10px;
        width: 24px;
        cursor: pointer;
        height: 24px;
        float: right;
        background: url(~@/assets/img/edit-icon.png) no-repeat 0 center;
      }

      .btns {
        float: right;
        margin-right: 24px;
        margin-bottom: 20px;

        .sml-btn {
          // color: #1e2480;
          // border-radius: 2px;
          // border: 1px solid #1e2480;
          height: 28px;
          line-height: 28px;
        }
      }

      .edit-input {
        width: 80%;

        .sml-btn {
          padding-left: 15px;
        }

        .sml-btn:hover {
          color: #1e2480;
        }

        /deep/.el-input__inner {
          min-width: 200px;
        }

        /deep/.el-input-group__append {
          min-width: 60px;
        }
      }
    }
  }
}

.detail-box {
  margin: 0 16px 0;
}

.inner-nav {
  margin: 8px 16px 0;
  height: 52px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;

  .nav {
    float: left;
    padding-left: 24px;

    .project-icon1::before {
      background: url(~@/assets/img/images/icon1.png) no-repeat;
      background-size: 22px 22px;
    }

    .project-icon1:hover::before,
    .project-icon1.active::before {
      background-image: url(~@/assets/img/images/icon1-hover.png);
    }

    .project-icon5::before {
      background: url(~@/assets/img/images/icon5.png) no-repeat;
      background-size: 22px 22px;
    }

    .project-icon5:hover::before,
    .project-icon5.active::before {
      background-image: url(~@/assets/img/images/icon5-hover.png);
    }

    .project-icon7::before {
      background: url(~@/assets/img/images/icon7.png) no-repeat;
      background-size: 22px 22px;
    }

    .project-icon7:hover::before,
    .project-icon7.active::before {
      background-image: url(~@/assets/img/images/icon7-hover.png);
    }

    .project-icon9::before {
      background: url(~@/assets/img/images/icon9.png) no-repeat;
      background-size: 22px 22px;
    }

    .project-icon9:hover::before,
    .project-icon9.active::before {
      background-image: url(~@/assets/img/images/icon9-hover.png);
    }

    .project-icon10::before {
      background: url(~@/assets/img/images/icon10.png) no-repeat;
      background-size: 22px 22px;
    }

    .project-icon10:hover::before,
    .project-icon10.active::before {
      background-image: url(~@/assets/img/images/icon10-hover.png);
    }
  }

  li {
    float: left;
    line-height: 52px;
    margin-right: 40px;
    cursor: pointer;
    color: #303133;

    &::before {
      content: " ";
      display: inline-block;
      // background: #333;
      width: 22px;
      height: 22px;
      vertical-align: middle;
    }
  }

  li.active {
    color: #1e2480;
    font-weight: bold;
    border-bottom: 2px solid #1e2480;
  }
}</style>
